import EventEmitter from "events";
import { command } from "./AtCommand";
import CommandQueue from "./CommandQueue";

class EventController extends EventEmitter {
    public moduleNum:number = 12; //模块的数量
    public current_module_id: number = 1 // 当前叫号的模块
    public type: string = "ten"
    public settingData:Array<Array<Record<string,string | number>>> = []
    public commandQueue: CommandQueue;
    constructor() {
        super();
        this.commandQueue = CommandQueue.getInstance();
        this.initModuleList()
    }

    public initModuleList() {
        this.settingData.push([
            {
                id: 1,
                name: "message.uv",
                normal_low: 100,
                normal_high: 5000,
                current_val: 1500,
            },
            {
                id: 2,
                name: "message.inf",
                normal_low: -40,
                normal_high: 150,
                current_val: 50
            },
            {
                id: 3,
                name: "message.tem",
                normal_low: -40,
                normal_high: 80,
                current_val: 50
            },
            {
                id: 4,
                name: "message.hum",
                normal_low: 0,
                normal_high: 90,
                current_val: 70
            },
            {
                id: 5,
                name: "message.pre",
                normal_low: 0,
                normal_high: 200 * 10,
                current_val: 121 * 10
            }
         ])
    }
    // 修改阈值
    changeVal(id,type,val) {
        try {
            this.settingData[0][type].current_val = val // 设置报警阈值
        } catch (error) {
            console.log(error)
        }
    }

}
const eventEmit = new EventController()

eventEmit.on("polling_call",(serialport)=>{
    setInterval(()=>{
        polling_call(serialport)
    },2000)
})
function polling_call(serialport) {
    if (eventEmit.current_module_id > eventEmit.moduleNum) {
        eventEmit.current_module_id = 1
    } 
    let id:any = null
    if (eventEmit.current_module_id <10) id = new String(eventEmit.current_module_id).padStart(2,'0')
    if (eventEmit.current_module_id >= 10) id = eventEmit.current_module_id.toString(16).padStart(2,'0')
    const hexStr: string = command.factoryType(eventEmit.type).replace("&&",id)
    let hexBuffer: Buffer = Buffer.from(hexStr,'hex')
    // 使用优先级0发送轮询命令（低优先级）
    eventEmit.commandQueue.addCommand(hexBuffer, 0);
    eventEmit.current_module_id++
}

export default eventEmit
